#include <iostream>
#include <unistd.h>
#include <pthread.h>
using namespace std;
// 临界资源
int ticket = 10000;
//互斥锁
pthread_mutex_t ticket_mutex = PTHREAD_MUTEX_INITIALIZER;
void *thread_routine(void *arg)
{
    int id = reinterpret_cast<long int>(arg);
    //多个进程同时读写num
    while (1)
    {
        //临界区
        //加锁
        pthread_mutex_lock(&ticket_mutex);
        if (ticket > 0)
        {
            cout << "thread_" << id << " get ticket: NO. " << ticket-- << endl;
            //解锁
            pthread_mutex_unlock(&ticket_mutex);
            usleep(999);
        }
        else
        {
            //解锁 确保每个路径都能正确解锁
            pthread_mutex_unlock(&ticket_mutex);
            cout << "thread_" << id << " no ticket left..." << endl;
            usleep(123);
            break;
        }
    }
}
int main()
{
    pthread_t threads[4];
    for (int i = 0; i < 4; i++)
        pthread_create(threads + i, nullptr, thread_routine, reinterpret_cast<void *>(i));
    for (int i = 0; i < 4; i++)
        pthread_join(threads[i], nullptr);
    return 0;
}